package org.ahuanlien.crm.service.impl;

import org.ahuanlien.crm.domain.CaseReportBill;
import org.ahuanlien.crm.domain.CaseReportBillItem;
import org.ahuanlien.crm.mapper.CaseReportBillItemMapper;
import org.ahuanlien.crm.query.CaseReportBillItemQueryObject;
import org.ahuanlien.crm.service.ICaseReportBillItemService;
import org.ahuanlien.crm.service.ICaseReportBillService;
import org.ahuanlien.crm.util.LogicException;
import org.ahuanlien.crm.util.PageResult;
import org.ahuanlien.crm.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.List;

@Service
public class CaseReportBillItemServiceImpl implements ICaseReportBillItemService {


	@Autowired
	private ICaseReportBillService caseReportBillService;
	@Autowired
	private CaseReportBillItemMapper caseReportBillItemMapper;

	public void saveOrUpdate(CaseReportBillItem caseReportBillItem) {

		/*获取到关联的报案单号*/
		String caseNumber = caseReportBillItem.getCaseNumber();
		CaseReportBill caseReportBill = caseReportBillService.getByCaseNumber(caseNumber);

		/*判断当前的报案单的状态是否是已受理, 如果不是已受理, 那么爆出异常, 提示用户当前明细不可以编辑*/
		if (caseReportBill.getStatus()!= CaseReportBill.ACCEPTED) {
			throw new LogicException("当前报案单不是已受理状态, 不可以编辑明细");
		}

		/*给明细单设置报案单中的信息*/
		caseReportBillItem.setInsuranceBillNumber(caseReportBill.getInsuranceBillNumber());
		caseReportBillItem.setPlateNumber(caseReportBill.getPlateNumber());
		caseReportBillItem.setReporterTelephone(caseReportBill.getTelephone());

		/*把车险报案明细 存入到数据库之中*/
		if (caseReportBillItem.getId()==null) {
			caseReportBillItem.setCaseHandler(UserContext.getCurrentUser());
			caseReportBillItemMapper.insert(caseReportBillItem);
		}else{
			caseReportBillItemMapper.updateByPrimaryKey(caseReportBillItem);
		}
	}

	public PageResult query(CaseReportBillItemQueryObject qo) {
		int count = caseReportBillItemMapper.queryForCount(qo);
		if (count == 0) {
			return new PageResult(count, Collections.EMPTY_LIST);
		}
		List<CaseReportBill> result = caseReportBillItemMapper.queryForList(qo);
		return new PageResult(count, result);
	}

	public CaseReportBillItem getByCaseNumber(String caseNumber) {
		return caseReportBillItemMapper.selectByCaseReportNumber(caseNumber);
	}
}
